package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;

    public ShopServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //解决缓存穿透问题
        //Shop shop = queryWithThrough(id);
        //使用工具类来处理缓存穿透问题
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.SECONDS);
        //解决缓存击穿问题
        //Shop shop = queryWithMutex(id);
        //解决缓存击穿逻辑过期处理
        //Shop shop = queryWithLogicalExpire(id);

        //使用缓存工具类中的方法
        if (shop == null)
        {
            return Result.fail("店铺不存在");
        }

        return Result.ok(shop);
    }
    //尝试获取锁
    private boolean tryLock(String key)
    {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key)
    {
        stringRedisTemplate.delete(key);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //逻辑过期解决缓存击穿问题
    public Shop queryWithLogicalExpire(Long id)
    {
        String shopKey = CACHE_SHOP_KEY + id;
        //1.从redis查询商品缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(shopKey);
        if(StrUtil.isBlank(shopJSON))
        {
            //若存在直接返回
            return null;
        }
        //若redis缓存命中
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        JSONObject shopData = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(shopData, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if(expireTime.isAfter(LocalDateTime.now()))
        {
            //未过期直接返回店铺信息
            return shop;
        }
        //已过期需要进行缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if(isLock)
        {
            if(expireTime.isAfter(LocalDateTime.now()))
            {
                //未过期直接返回店铺信息
                return shop;
            }
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                try {
                    //重建缓存
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });

        }


        //2.若缓存中不存在则需要查询数据库
        return JSONUtil.toBean(shopData, Shop.class);
    }

    //解决缓存穿透问题
    public Shop queryWithThrough(Long id)
    {
        String shopKey = CACHE_SHOP_KEY + id;
        //1.从redis查询商品缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(shopKey);
        if(StrUtil.isNotBlank(shopJSON))
        {
            //若存在直接返回
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        //若店铺信息为空字符串
        if(shopJSON != null)
        {
            return null;
        }
        //2.若缓存中不存在则需要查询数据库
        Shop shop = getById(id);
        if(shop == null)
        {
            //将空的店铺信息放入缓存
            stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //将商品信息放入缓存
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    //解决缓存击穿问题
    public Shop queryWithMutex(Long id)
    {
        String shopKey = CACHE_SHOP_KEY + id;
        //1.从redis查询商品缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(shopKey);
        if(StrUtil.isNotBlank(shopJSON))
        {
            //若存在直接返回
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        //若店铺信息为空字符串
        if(shopJSON != null)
        {
            return null;
        }
        //实现缓存重建
        //获取互斥锁
        String lockKey =LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //判断是否成功获取到锁
            //获取锁失败休眠并且重试
            if(!isLock)
            {
                Thread.sleep(10);
                queryWithMutex(id);
            }
            //若获取锁成功则需要根据id去查询数据库
            shop = getById(id);
            Thread.sleep(200);
            if(shop == null)
            {
                //将空的店铺信息放入缓存
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //将商品信息放入缓存
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放锁
            unLock(lockKey);
        }
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireTime)
    {
        //查询店铺数据
        Shop shop = getById(id);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }


    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null)
        {
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
